// 按推荐教师汇总

package student

import (
	"api/common"
	"api/common/logger"
	"api/common/orm"
	"api/common/web"
	"net/http"
	"sort"
	"strings"
)

// @TagName 按推荐教师汇总
// @Controller RecommendController
type RecommendController struct{}

// @Title 学生列表数据
// @Route /recommend/list --> List
// @Method post
func (this *RecommendController) List(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	inputJson, msg := web.TokenCheckRequest(r)
	if msg != nil {
		web.ServeJSON(w, msg)
		return
	}

	wheres, limit := web.SerachJsonToSql(inputJson)
	where := " where `status` = 5 and `exit` = false" // 5: 交费成功，且未退学
	if len(wheres) > 0 {
		where += " and "
		where += strings.Join(wheres, " and ")
	}

	recommend := inputJson["recommend"]
	if recommend != nil {
		where += " and recommend = '" + common.ToStr(recommend) + "'"
	}

	type Counts struct {
		Total uint32 `json:"total"`

		Recommend1 uint32 `json:"recommend1"`
		Recommend0 uint32 `json:"recommend0"`
	}
	counts := &Counts{}
	sql := "select" +
		" (select count(1) from student_info" + where + ") total," +
		" (select count(1) from student_info" + where + " and recommend != '') recommend1," +
		" (select count(1) from student_info" + where + " and recommend  = '') recommend0"
	conn := orm.NewOrm()
	err := conn.Raw(sql).QueryRow(counts)
	if err != nil {
		logger.Error("查询记录数量发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "查询记录数量发生错误" + err.Error(), 1})
		return
	}

	data := []map[string]interface{}{}
	if counts.Total > 0 {
		sql = "select id, `name`, sex, phone, id_card_num, special_id, type, lodging, recommend" +
			" from student_info" + where +
			" order by recommend desc, special_id, lodging desc, sex desc, add_time" + limit
		data, err = conn.Raw(sql).QueryMaps()
		if err != nil {
			logger.Error("查询记录发生错误", err)
			web.ServeJSON(w, web.JsonMsg{false, "查询记录发生错误" + err.Error(), 1})
			return
		}
	}

	result := map[string]interface{}{}
	result["status"] = 0
	result["success"] = true
	result["msg"] = "查询成功"
	result["data"] = data
	result["counts"] = counts
	web.ServeJSON(w, result)
}

// @Title 推荐教师列表数据
// @Route /recommend/listTeacher --> ListTeacher
// @Method post
func (this *RecommendController) ListTeacher(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	_, msg := web.TokenCheckRequest(r)
	if msg != nil {
		web.ServeJSON(w, msg)
		return
	}

	where := "`status` = 5 and `exit` = false" // 5: 交费成功，且未退学

	// 获取推荐教师列表数据
	sql := "select recommend from student_info" +
		" where " + where + " and char_length(recommend) >= 2" +
		" order by recommend desc"
	conn := orm.NewOrm()
	teacherData, err := conn.Raw(sql).QueryMaps()
	if err != nil {
		logger.Error("查询记录发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "查询记录发生错误" + err.Error(), 1})
		return
	}

	// 获取未经老师推荐的学生人数(学生自己报名)
	recommend0 := 0
	sql = "select count(1) from student_info" +
		" where `status` = 5 and `exit` = false and recommend  = ''"
	err = conn.Raw(sql).QueryRow(&recommend0)
	if err != nil {
		logger.Error("获取未经老师推荐的学生人数发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取未经老师推荐的学生人数发生错误" + err.Error(), 1})
		return
	}

	data := [][]interface{}{
		{"未经推荐", recommend0, 0},
	}
	obj := map[string]interface{}{}

	// 统计教师招了几个学生
	if len(teacherData) > 0 {
		for i := 0; i < len(teacherData); i += 1 {
			item := teacherData[i]
			teacherName := common.ToStr(item["recommend"])
			if obj[teacherName] == nil {
				obj[teacherName] = 1
			} else {
				count := obj[teacherName].(int)
				obj[teacherName] = count + 1
			}
		}

		for key, value := range obj {
			child := []interface{}{}
			// 教师姓名，招生人数，排行榜
			child = append(child, key, value, 1)
			data = append(data, child)
		}

		// 按招生人数倒排序
		sort.Slice(data, func(i, j int) bool {
			a := data[i][1].(int)
			b := data[j][1].(int)
			return a >= b
		})

		// 计算排行榜
		var beforeCount interface{}
		for i := 0; i < len(data); i += 1 {
			item := data[i]
			if item[2] == 1 {
				beforeCount = item[1]
				break
			}
		}
		rank := 1
		for i := 0; i < len(data); i += 1 {
			item := data[i]
			if item[2] == 0 {
				// 未经推荐不计入排名
				continue
			}

			if item[1] != beforeCount {
				beforeCount = item[1]
				rank += 1
			}
			item[2] = rank
		}
	}

	obj = map[string]interface{}{}
	obj["status"] = 0
	obj["success"] = true
	obj["msg"] = "查询成功"
	obj["data"] = data
	web.ServeJSON(w, obj)
}
